<template>
    <div>
        <!-- 白皮书上传弹框 -->
        <el-dialog
            :visible.sync="dialogVisible"
            :close-on-click-modal="false"
            width="40%">
            <el-form ref="form" :model="form" label-width="80px">
                <el-form-item label="文章名称" prop="article_name">
                    <el-input v-model="form.article_name " size="mini" placeholder="输入文章名称" style="width:100%;"></el-input>
                </el-form-item>
                <el-form-item label="文章简介" prop="summary">
                    <el-input type="textarea" v-model="form.summary" placeholder="请输入简介"></el-input>
                </el-form-item>
                <el-form-item label="展示方式" prop="isdisplay">
                    <el-checkbox v-model="form.is_display">在首页展示</el-checkbox>
                </el-form-item>
                <el-form-item label="文章上传">
                    <form ref="uploadForm" id="uploadForm" action='upload_file' role="form" method="post" enctype=multipart/form-data>
                        <input type="file" ref="fileUp" name="file" @change="filechange">
                    </form>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                    <el-button size="mini" type="primary" @click.prevent="submitFile">提 交</el-button>
                    <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
            </span>

        </el-dialog>
        <!-- 白皮书上传弹框结束 -->    
        <el-row :gutter="20">
            <el-col :span="24">
                <el-form :inline="true"  @submit.native.prevent>
                    <el-form-item label="">
                        <el-button @click="showAddDialog" size="mini">添加文章</el-button>
                    </el-form-item>
                    <div class="rightWay">
                        <el-form-item>
                        <el-input
                            @keyup.enter.native="gogetReport"
                            placeholder="文章名称"
                            size="mini"
                            v-model="search"
                            clearable>
                        </el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button @click="getReport(1)" type="primary" size="mini">搜索</el-button>
                        </el-form-item>
                    </div>
                </el-form>
            </el-col>
        </el-row>
        <el-table
            :data="tableData"
            border
            style="width: 100%">
            <el-table-column
            prop="article_code"
            label="文章ID"
            width="140">
            </el-table-column>
            <el-table-column
            prop="article_name"
            label="文章名称">
            </el-table-column>
            <el-table-column
            prop="create"
            label="上传日期"
            width="160">
            </el-table-column>
            <el-table-column
            prop="creator"
            label="上传人"
            width="100">
            </el-table-column>

            <el-table-column
            label="首页展示"
            width="100" style="text-align: center;">
                <template slot-scope="scope">
                    <el-tag type="success" v-if="scope.row.is_display">已展示</el-tag>
                    <el-tag type="info" v-if="!scope.row.is_display">未展示</el-tag>
                </template>
            </el-table-column>

            <el-table-column
            label="操作"
            width="140">
            <template slot-scope="scope">
                <el-button style="color:red;" @click="handleDelete(scope.row)" type="text" size="small">删除</el-button>
                <el-button type="text" size="small" @click="changeDisplay(scope.row)">切换展示</el-button>
            </template>
            </el-table-column>
        </el-table>
        <el-pagination
        @current-change="handleSizeChange"
        class="paganitionRight"
        :page-size="10"
        :pager-count="9"
        layout="total, prev, pager, next"
        :total="totalCount">
        </el-pagination>
    </div>
</template>
<script>
export default {
    name: 'purpleSearch',
    data () {
        return {
            dialogVisible: false,
            search: '',
            tableData: [],
            totalCount: 0, // 总数据条数
            curIndex: 1, // 当前页面
            id: '',
            form:{
                article_name :'',
                file:'',
                summary:'',
                is_display: false
            }
        }
    },
    methods: {
        showAddDialog(){
            // 清空文章表单
            this.dialogVisible = true;
            this.$nextTick(()=>{
                this.$refs.uploadForm.reset();
            })
            this.form.article_name = '';
            this.form.summary = '';
        },
        // 切换状态
        changeDisplay(row){
            this.$confirm('此操作将切换展示状态, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let data = {
                    is_display: !row.is_display
                }
                this.$axios.put(`/api/baipishu/${row.id}/`, JSON.stringify(data))
                .then((res)=>{
                    if(res.status === 200){
                        this.$message({
                            type: 'success',
                            message: '修改成功!'
                        });
                    }
                    this.getReport();
                }).catch((error)=>{
                    console.log(error);
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            })
        },
        // 删除文章
        handleDelete(row){
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.delete(`/api/baipishu/${row.id}/`)
                .then((res)=>{
                    if(res.status === 204){
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                    }
                    this.getReport();
                }).catch((error)=>{
                    this.getReport();
                    console.log(error);
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            })
        },
        submitFile () {
            let id = this.$route.query.id
            let formData = new FormData();
            let upfile = this.$refs.fileUp;
            const pattern = /.*\.pdf/i;

            if(pattern.test(upfile.value)){
                formData.append("article_name", this.form.article_name);
                formData.append("summary", this.form.summary);
                formData.append("is_display", this.form.is_display);
                formData.append("file", upfile.files[0]);


                this.$axios.post(`/api/baipishu/`, formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        'Authorization': localStorage.getItem('Authorization')
                    }
                })
                .then((res) => {
                    console.log(res);
                    if (res.status === 201) {
                        this.$message('上传成功', 'success');
                        this.dialogVisible = false;
                        this.getReport(1);
                    }else{
                    this.$message('上传失败','error');
                    }
                }).catch((err) => {
                    this.$message('上传失败','error');
                });

            }else{
                // 非pdf文档提示
                this.$message({
                    message: '只支持pdf文件文件上传',
                    type:'info'
                });
                return false;
            }
        },
        handleSizeChange(page) {
            this.curIndex = page;
            this.getReport(page);
        },
        getReport(page){
            this.curIndex = page === 1 ? 1 : page;
            this.$axios.get(`/api/baipishu/`, {
                    params: {
                        search: this.search,
                        page: this.curIndex
                    }
                }).then(res => {
                    if(res.status === 200 && res.data.results.length >0){
                        this.tableData = res.data.results;
                        this.totalCount = res.data.count;
                    }
            })
        },
        gogetReport(){
            this.getReport(1);
        },
        filechange(){
            let upfile = this.$refs.fileUp;
            const pattern = /.*\.pdf/i;
            console.log(upfile)
            if(pattern.test(upfile.value)){
                let temparray = upfile.value.split("\\");
                let filename = temparray[temparray.length-1].split('.')[0];
                this.form.article_name = filename;
            }else{
                // 非pdf文档提示
                this.$message({
                    message: '只支持pdf文件文件上传',
                    type:'info'
                });
                return false;
            }
        }
    },
    mounted(){
        this.getReport(1);
    }
}
</script>
<style scoped lang="scss">
.rightWay {
    float: right;
}
</style>

